package com.wuwei.elearning.pdf;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.Texts;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
public class TextToWord {

    private String templateFilePath = "E:\\audio\\template.docx";

    private static String removeSpacesBetween(String text, String start, String end) {
        String pattern = start + "\\s+" + end;
        return text.replaceAll(pattern, start + end);
    }

    /*
    1.逐次获取txt内的文本
    2.逐次把txt内的文本写到word中
     */
    @Test
    public void test(){
        String txtPath = "E:\\audio\\text";
        File folder = new File(txtPath);
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                String name = file.getName();
                try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                    String line;
                    StringBuilder stringBuilder = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        // 在这里处理每行文本，可以写入Word或者进行其他操作
                        stringBuilder.append(line).append("\n");
                    }
                    String text = stringBuilder.toString();
                    int indexOf = name.indexOf(".");
                    String substring = name.substring(0, indexOf);

                    String destFilePath = "E:\\audio\\pdf\\"+substring+".docx";
                    Map<String, Object> datas = new HashMap<String, Object>();
                    datas.put("var", Texts.of(text).create());
                    XWPFTemplate compile = XWPFTemplate.compile(templateFilePath);
                    compile.render(datas);
                    compile.writeToFile(destFilePath);
                    stringBuilder.setLength(0);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test1(){
        String txtPath = "E:\\audio\\pdf";
        File folder = new File(txtPath);
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                // 获取文件的当前名称
                String name = file.getName();

                System.out.println(name);
                // 检查文件是否是.docx文件
                if (name.toLowerCase().endsWith(".docx")) {
                    convertDocxToPdf(file);
                }
            }
        }
    }

    private void convertDocxToPdf(File docxFile) {
        // 获取不带扩展名的文件名
        String fileNameWithoutExtension = docxFile.getName().substring(0, docxFile.getName().lastIndexOf('.'));
        // 构造输出PDF文件路径
        String pdfFilePath = docxFile.getParent() + File.separator + fileNameWithoutExtension + ".pdf";

        // 调用LibreOffice进行转换
        ProcessBuilder processBuilder = new ProcessBuilder(
                "soffice",
                "--headless",
                "--convert-to", "pdf",
                "--outdir", docxFile.getParent(),
                docxFile.getAbsolutePath()
        );
        try {
            Process process = processBuilder.start();
            process.waitFor();
            System.out.println("Converted: " + docxFile.getName() + " to " + pdfFilePath);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            System.out.println("Failed to convert: " + docxFile.getName());
        }
    }
}
